<template>
  <div class="app-container employeeWorker">
    <FixedBar>
<!--      <el-popconfirm v-if="handleType !== 'view' && isEnd" title="确认保存？" @confirm="onSubmit" style="margin-right: 10px">-->
<!--        <el-button slot="reference" type="primary">保存</el-button>-->
<!--      </el-popconfirm>-->
      <el-button v-if="handleType !== 'view' && isEnd" type="primary" @click="confirmSubmit">保存</el-button>
      <el-button v-if="handleType !== 'view' && !isEnd" type="primary" @click="onSubmit">提交审核</el-button>

<!--      <el-button v-if="handleType === 'view' && isEnd" type="primary" @click="onAuditLog">审核记录</el-button>-->
      <el-button v-if="handleType === 'view'" type="primary" @click="onAuditLog">审核记录</el-button>
      <el-button @click="onCancel">取消</el-button>
    </FixedBar>
    <el-card class="mt10 box-card">
      <StatusSteps v-if="order" :active="order.taskNode" :status="order.status"></StatusSteps>
    </el-card>

    <el-form :model="orderForm" :rules="rules" ref="orderForm" label-width="auto" size="mini" :disabled="handleType === 'view'">
      <el-card class="mt10 box-card">
        <div slot="header" class="clearfix">
          <span>业务信息</span>
          <el-tooltip placement="top" class="ml5">
            <div slot="content">
              预估业务量：预测24h量-预测12h量+省内未发+班组遗留<br/>
              建议人数：当班预测量 / 对应运营方案设置的人效<br/>
              预估用工（业务）：人员配置中“实际人数”的汇总值<br/>
              预估用工（人事）：排班人数 + 零工人数<br/>
              预估人效（人事）：当班预测量 / 人事预估用工数<br/>
              预估用工超额：（人事预估用工数 - 建议人数）/建议人数*100%
            </div>
            <el-link icon="el-icon-question"></el-link>
          </el-tooltip>
        </div>
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="需求单号" prop="operationalOrderCode">
              <el-input v-model="orderForm.operationalOrderCode" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="用工日期" prop="workTime">
              <el-date-picker type="date" format="yyyy-MM-dd" placeholder="选择日期" :picker-options="pickerOptions" v-model="orderForm.workTime" style="width: 100%;" :disabled="true"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="班次" prop="timeShiftId">
              <el-select ref="timeShiftId" v-model="orderForm.timeShiftId" filterable placeholder="请选择"  :disabled="true" >
                <el-option
                  v-for="item in timeShiftList"
                  :key="item.timeShiftId"
                  :label="item.timeShiftName"
                  :value="item.timeShiftId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="班组" prop="groupId">
              <el-select ref="groupId" v-model="orderForm.groupId" filterable placeholder="请选择" :disabled="isOdd" >
                <el-option
                  v-for="item in groupList"
                  :key="item.workGroupId"
                  :label="item.workGroupName"
                  :value="item.workGroupId"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24"><el-divider></el-divider></el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="预测24h" prop="forecast24">
              <el-input type="number" style="width: 100%" v-model="orderForm.forecast24" min="0" :disabled="true">
                <template slot="append">万件</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="预测12h" prop="forecast12">
              <el-input style="width: 100%" v-model="orderForm.forecast12" :min="0" :disabled="true">
                <template slot="append">万件</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="省内未发" prop="notSentNumber">
              <el-input style="width: 100%" v-model="orderForm.notSentNumber" :min="0" :disabled="true">
                <template slot="append">万件</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="待卸量" prop="quantityToUnloaded">
              <el-input style="width: 100%" v-model="orderForm.quantityToUnloaded" :min="0" :disabled="true">
                <template slot="append">万件</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="车辆数" prop="carNumber">
              <el-input style="width: 100%" v-model.number="orderForm.carNumber" :min="0" :disabled="true">
                <template slot="append">辆</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="班组遗留" prop="bequeathNumber">
              <el-input style="width: 100%" v-model="orderForm.bequeathNumber" :min="0" :disabled="true">
                <template slot="append">万件</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="预估业务量" prop="estimateBusinessNumber">
              <el-input style="width: 100%" v-model="orderForm.estimateBusinessNumber" :disabled="true">
                <template slot="append">万件</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="当班预测量" prop="groupEstimateNumber">
              <el-input style="width: 100%" @change="changeGroupEstimate" v-model="orderForm.groupEstimateNumber"  :disabled="isOdd">
                <template slot="append">万件</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24"><el-divider></el-divider></el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="运营方案" prop="schemeConfigurationId">
              <el-select :disabled="strategyFa || isOdd" ref="schemeConfigurationId" @change="handleChangeScheme" v-model="orderForm.schemeConfigurationId" filterable placeholder="请选择"  >
                <el-option
                  v-for="item in schemeList"
                  :key="item.id"
                  :label="item.programmeName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="标准人数" prop="standardNumber">
              <el-input style="width: 100%" v-model.number="orderForm.standardNumber" :min="0" :disabled="true">
                <template slot="append">人</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="建议人数" prop="recommendedNumber">
              <el-input style="width: 100%" v-model.number="orderForm.recommendedNumber" :min="0" :disabled="true">
                <template slot="append">人</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="预估用工" prop="estimateWorkerNumber">
              <el-input style="width: 100%" v-model.number="orderForm.estimateWorkerNumber" :min="0" :disabled="true">
                <template slot="append">人</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="预估人效" prop="estimateEffect">
              <el-input style="width: 100%" v-model.number="orderForm.estimateEffect" :min="0" :disabled="true">
                <template slot="append">件</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="零工比例男" prop="oddJobMale">
              <el-input v-model.number="orderForm.oddJobMale" :min="0"  :disabled="isOdd">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="零工比例女" prop="oddJobFemale">
              <el-input v-model.number="orderForm.oddJobFemale" :min="0"  :disabled="isOdd">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="orderForm.remark" type="textarea" :rows="1"  :disabled="isOdd">
              </el-input>
            </el-form-item>
          </el-col>

        </el-row>
      </el-card>

      <el-card class="mt10 box-card" v-if="isOdd">
        <div slot="header" class="clearfix">
          <span>零工预测（人事）</span>
        </div>
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="排班人数" prop="personnelRosterNumber">
              <el-input v-model="orderForm.personnelRosterNumber" @change="getComputedOdd" :disabled="isEnd">
                <template slot="append">人</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="预测零工数" prop="personnelOddNumber">
              <el-input v-model="orderForm.personnelOddNumber" @change="getComputedOdd" :disabled="isEnd">
                <template slot="append">人</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="预估用工" prop="personnelEstimateNumber">
              <el-input v-model="orderForm.personnelEstimateNumber" :disabled="true">
                <template slot="append">人</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="预估人效" prop="personnelEstimatePercentage">
              <el-input v-model="orderForm.personnelEstimatePercentage" :disabled="true">
                <template slot="append">件</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="用工超额比" prop="personnelExcessPercentage">
              <el-input v-model="orderForm.personnelExcessPercentage" :disabled="true">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="用工超控比" prop="personnelOverridePercentage">
              <el-input v-model="orderForm.personnelOverridePercentage" :disabled="true">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="mt10 box-card" v-if="isEnd">
        <div slot="header" class="clearfix">
          <span>用工完结</span>
        </div>
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="出勤长期工" prop="attendanceWorkerNumber">
              <el-input v-model="orderForm.attendanceWorkerNumber" :disabled="true">
                <template slot="append">人</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="出勤临时工" prop="attendanceOddNumber">
              <el-input v-model="orderForm.attendanceOddNumber" :disabled="true">
                <template slot="append">人</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="实际完成" prop="actualFinalNumber" >
              <el-input v-model="orderForm.actualFinalNumber" @change="getComputedEnd">
                <template slot="append">万件</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="实际人效" prop="actualWorkerNumber">
              <el-input v-model="orderForm.actualWorkerNumber" :disabled="true">
                <template slot="append">件</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

    </el-form>

    <el-card class="mt10 box-card">
      <div slot="header" class="clearfix">
        <span>人员配置</span>
      </div>
      <el-table
        class="staffTable"
        :data="staffData"
        :span-method="objectSpanMethod"
        border
        style="width: 100%">
        <el-table-column
          prop="regionName"
          label="区域"
          width="180">
          <template slot-scope="scope">
            <span :class="{ textDisable : scope.row.regionDisable }">{{scope.row.regionName}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="groupName"
          label="组别">
          <template slot-scope="scope">
            <span :class="{ textDisable : scope.row.groupDisable }">{{scope.row.groupName}}</span>
          </template>
        </el-table-column>
        <!--        <el-table-column-->
        <!--          prop="groupNumber"-->
        <!--          label="组别人数">-->
        <!--        </el-table-column>-->
        <el-table-column
          prop="postName"
          label="岗位">
          <template slot-scope="scope">
            <span :class="{ textDisable : scope.row.postDisable }">{{scope.row.postName}}</span>
          </template>
        </el-table-column>
        <el-table-column
          width="150px"
          prop="postNumber"
          label="业务 - 计划人数">
          <template slot-scope="scope">
            <span>{{scope.row.postNumber ? scope.row.postNumber : 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          width="150px"
          prop="postNumber"
          label="业务 - 预估人数">
          <template slot-scope="scope">
            <span v-if="handleType === 'view' || isOdd">{{scope.row.estimatePostNumber ? scope.row.estimatePostNumber : 0}}</span>
            <el-input-number v-else size="mini" controls-position="right" v-model="scope.row.estimatePostNumber" @change="handleChange(scope.row)" style="width: 100%" :min="0"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          prop="quota"
          width="200px"
          label="汇总人数">
          <template slot-scope="scope">
              <span :class="{ textDisable : scope.row.regionDisable }">
                计划总人数：{{scope.row.quota ? scope.row.quota : 0}}<br/>
                预估总人数：{{scope.row.estimateQuota ? scope.row.estimateQuota : 0}}<br/>
                人数总差额：{{ getDiffer(scope.row.quota , scope.row.estimateQuota)}}<br/>
              </span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="mt10 box-card">
      <div slot="header" class="clearfix">
        <span>设备配置</span>
      </div>
      <div class="device-wrap">
        <div class="mt10">
          <span class="itemStatus">启用</span>
          <span class="itemStatus red">停用</span>
        </div>
        <el-table
          v-if="deviceData && deviceData.length"
          :data="deviceData"
          border
          style="width: 100%;margin-top: 10px">
          <el-table-column
            prop="equipmentName"
            label="作业时间"
            width="180">
          </el-table-column>
          <el-table-column
            v-for="item in deviceTime"
            :prop="`${item}`"
            :label="`${item}`">
            <template slot-scope="scope">
              <div class="status" :class="{green:scope.row[item] == 1,red:scope.row[item] == 0}"></div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <el-card class="mt10 box-card">
      <div slot="header" class="clearfix">
        <span>附件</span>
      </div>
      <div style="max-width: 500px" v-if="handleType === 'view' || isOdd">
        <div v-for="(item,index) in fileList">
          <!--          {{index+1}}、<el-link type="primary" target="_blank" :href="item"><i class="el-icon-link"></i>附件{{index+1}}</el-link>-->
          {{index+1}}、<el-link type="primary" @click="handleAnnex(item.fileName)"><i class="el-icon-link"></i>{{item.name}}</el-link>
        </div>
      </div>
      <div style="max-width: 500px" v-else>
        <el-upload
          :limit="2"
          class="upload-annex"
          :headers="upload.headers"
          :action="upload.url"
          :on-preview="handleUploadPreview"
          :on-change="handleUploadChange"
          :on-remove="handleUploadRemove"
          :on-exceed="handleUploadExceed"
          :file-list="fileList">
          <el-button size="small" type="primary">上传文件</el-button>
          <div slot="tip" class="el-upload__tip">最多上传两个附件</div>
          <!--            <div slot="tip" class="el-upload__tip">支持扩展名：.rar .zip .doc .docx .pdf .jpg</div>-->
        </el-upload>
      </div>


    </el-card>

    <!-- 日志对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-table :data="auditLogs">
        <el-table-column label="需求阶段" align="center" prop="operationalStage">
          <template slot-scope="scope">
            <span>{{ getTaskNode(scope.row.operationalStage) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核结果" align="center" prop="auditResult">
          <template slot-scope="scope">
            <span v-if="scope.row.auditResult === 2">同意</span>
            <span v-else-if="scope.row.auditResult === 3">驳回</span>
            <span v-else-if="scope.row.auditResult === 4">撤销</span>
            <span v-else>{{scope.row.auditResult}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作人"  align="center" prop="auditName" />
        <el-table-column label="所属部门" align="center" prop="auditDeptName" >
          <template slot-scope="scope">
            <span>{{ scope.row.auditDeptName ? scope.row.auditDeptName : '— —' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" >
          <template slot-scope="scope">
            <span>{{ scope.row.remark ? scope.row.remark : '— —' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作时间" align="center" min-width="120" prop="auditTime" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    getFaResult,
    getWorkerNumber,
    getAttendanceInformation,
    getTimeShiftAndDep,
    getTimShiftInfo,
    operationalAdd,
    operationalUpdate,
    getOperationalDetail,
    delProcessInstance
  } from "@/api/plan/employee";
  import FixedBar from '@/components/FixedBar';
  import { getSchemeDetail } from "@/api/job/scheme";
  import { parseTime } from "@/utils/ruoyi";
  import StatusSteps from "../components/statusSteps"
  import {getToken} from "@/utils/auth";
  export default {
    name: "employeeAdd",
    components:{
      FixedBar,
      StatusSteps
    },
    created() {
      //获取初始化配置
      // this.getEquipmentsAndDeps();
      // console.log(this.id,this.handleType)


      //获取班次
      // this.getTimShiftInfo();
      //获取班组 班次 策略 方案
      this.getTimeShiftAndDep();
    },
    props:{
      handleType: {   //操作类型
        default: 'edit',
        type: String
      },
      isOdd: {   //是否是零工
        default: false,
        type: Boolean
      },
      isEnd: {   //是否是用工完结
        default: false,
        type: Boolean
      },
      id: {
        type: [Number,String],
        default: null
      }

    },
    data() {
      const positiveNumber = (rule, value, callback) => {
        if(Number(value) >= 0){
          callback();
        }else{
          callback(new Error("请输入有效数值"));
        }
      };
      return {
        taskOptions: [
          { value: 0, label: '件量预测' },
          { value: 1, label: '件量预测' },
          { value: 2, label: '用工评估' },
          { value: 3, label: '零工预测' },
          { value: 4, label: '方案审核' },
          { value: 5, label: '用工完结' }
        ],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        auditLogs: null,
        upload:{
          // 设置上传的请求头部
          headers: {Authorization: "Bearer " + getToken()},
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/common/upload"
        },
        //附件文件列表
        fileList: [],
        timeShiftList: null,
        groupList: null,
        schemeList: null, //方案列表
        order: null,  //订单数据
        strategyFa: null,  //方案策略 手动or自动
        currScheme: null,  //当前方案
        staffData: null,  //人员配置
        deviceData: null,  //设备配置
        deviceTime: null,  //设备配置
        orderForm: {
          operationalOrderCode: null,
          workTime: new Date().getTime()+24*60*60*1000,
          timeShiftId: null,
          groupId: null,
          forecast24: null,
          forecast12: null,
          notSentNumber: null,
          quantityToUnloaded: null,
          carNumber: null,
          bequeathNumber: null,
          estimateBusinessNumber: null,
          groupEstimateNumber: null,
          schemeConfigurationId: null,
          standardNumber: null,
          recommendedNumber: null,
          estimateWorkerNumber: null, //预估用工
          estimateEffect: null, //预估人效
          oddJobFemale: null, //男
          oddJobMale: null, //女
          remark: null,
          personnelRosterNumber: null, //排班人数
          personnelOddNumber: null, //预测零工数
          personnelEstimateNumber: null, //预估用工
          personnelEstimatePercentage: null, //预估人效比(人事)
          personnelExcessPercentage: null, //用工超额比
          personnelOverridePercentage: null, //用工超控比

          attendanceWorkerNumber: null, //出勤长期工
          attendanceOddNumber: null, //出勤临时工
          actualFinalNumber: null, //实际完成
          actualWorkerNumber: null, //实际人效
        },
        rules: {
          operationalOrderCode: [
            { required: true, trigger: 'blur' },
          ],
          workTime: [
            { required: true, message: '请选择', trigger: 'change' },
          ],
          standardEffect: [
            { required: true, message: '请输入标准人效', trigger: 'blur' },
            { type: 'number', message: '标准人效必须为数字值'}
          ],
          timeShiftId: [
            { required: true, message: '请选择', trigger: 'change' },
          ],
          groupId: [
            { required: true, message: '请选择', trigger: 'change' },
          ],
          forecast24: [
            { required: true, message: '请输入', trigger: 'blur' },
          ],
          forecast12: [
            { required: true, message: '请输入', trigger: 'blur' },
          ],
          notSentNumber: [
            { required: true, message: '请输入', trigger: 'blur' },
          ],
          quantityToUnloaded: [
            { required: true, message: '请输入', trigger: 'blur' },
          ],
          carNumber: [
            { required: true, message: '请输入', trigger: 'blur' },
            { type: 'number', message: '必须为数字值'}
          ],
          bequeathNumber: [
            { required: true, message: '请输入', trigger: 'blur' },
          ],
          groupEstimateNumber: [
            { required: true, message: '请输入', trigger: 'blur' },
            { validator: positiveNumber, trigger: 'blur' },
          ],
          schemeConfigurationId: [
            { required: true, message: '请选择', trigger: 'change' },
          ],
          standardNumber: [
            { required: true, message: '请输入', trigger: 'blur' },
          ],
          recommendedNumber: [
            { required: true, message: '请输入', trigger: 'blur' },
          ],
          estimateWorkerNumber: [
            { required: true, message: '请输入', trigger: 'blur' },
          ],
          oddJobFemale: [
            { required: true, message: '请输入', trigger: 'blur' },
            { validator: positiveNumber, trigger: 'blur' },
          ],
          oddJobMale: [
            { required: true, message: '请输入', trigger: 'blur' },
            { validator: positiveNumber, trigger: 'blur' },
          ],

          personnelRosterNumber: [
            { required: true, message: '请输入', trigger: 'blur' },
            { validator: positiveNumber, trigger: 'blur' },
          ],
          personnelOddNumber: [
            { required: true, message: '请输入', trigger: 'blur' },
            { validator: positiveNumber, trigger: 'blur' },
          ],
          personnelEstimateNumber: [
            { required: true, message: '请输入', trigger: 'blur' },
          ],
          personnelEstimatePercentage: [
            { required: true, message: '请输入', trigger: 'blur' },
          ],
          personnelExcessPercentage: [
            { required: true, message: '请输入', trigger: 'blur' },
          ],
          personnelOverridePercentage: [
            { required: true, message: '请输入', trigger: 'blur' },
          ],
          attendanceWorkerNumber: [
            { required: true, message: '请输入', trigger: 'blur' },
          ],
          attendanceOddNumber: [
            { required: true, message: '请输入', trigger: 'blur' },
          ],
          actualFinalNumber: [
            { required: true, message: '请输入', trigger: 'blur' },
            { validator: positiveNumber, trigger: 'blur' },
          ],
        },
        //禁用时间
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          }
        },
      };
    },
    computed: {
      getTaskNode: function(){
        return function (node) {
          let nodeText = node;
          this.taskOptions.forEach(item=>{
            if(item.value === node){
              nodeText = item.label;
            }
          });
          return nodeText;
        }

      },
      estimateBusinessNumber: function () {
        const { forecast24, forecast12, notSentNumber, bequeathNumber } = this.orderForm;
        const estimateBusinessNumber = forecast24*1 + forecast12*1 + notSentNumber*1 + bequeathNumber*1;
        // this.orderForm = { ...this.orderForm, estimateBusinessNumber: estimateBusinessNumber}
        return estimateBusinessNumber.toFixed(2)
      },
      areaNum(){  //获取区域数组
        return new Set(this.staffData.map(o => o.regionName));
      },
      groupNum(){  //获取组别数组
        return new Set(this.staffData.map(o => o.groupName));
      }
    },

    methods: {
      /** 下载附件操作 */
      handleAnnex(fileName) {
        // console.log(fileName)
        window.location.href = process.env.VUE_APP_BASE_API + "/common/download/resource?resource=" + encodeURI(fileName) + "&delete=" + false;
      },
      //编辑
      operationalUpdate(params){
        operationalUpdate(params).then(res=>{
          console.log(res)
          if(res && res.code === 200){
            this.$router.replace({path:"/plan/employee"});
          }
        })
      },

      //审核记录
      onAuditLog(){
        // console.log('----');
        this.open = true;
        this.title = '审核记录'
      },
      // 取消按钮
      cancel() {
        this.open = false;
      },
      //取消
      onCancel(){
        this.$router.replace({path:"/plan/employee"});
      },
      //确认保存
      confirmSubmit(){
        this.$confirm('是否确认保存?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(()=> {
          this.onSubmit()
        }).catch(() => {});
      },
      //保存
      onSubmit: function(){

        this.$refs["orderForm"].validate(valid => {
          if (valid) {

            const { id , taskNode , status, operationalOrderCode } = this.order || {};
            const { groupId,groupEstimateNumber,standardNumber,
              schemeConfigurationId, recommendedNumber,estimateWorkerNumber,
              estimateEffect,oddJobMale,oddJobFemale,
              remark,
              personnelRosterNumber,personnelOddNumber,personnelEstimateNumber, personnelEstimatePercentage,
              personnelExcessPercentage,personnelOverridePercentage,
              attendanceWorkerNumber,attendanceOddNumber,actualFinalNumber,actualWorkerNumber,
            } = this.orderForm;

            let params = {};
            if(id){
              params = {  id ,taskNode, status, orderCode:operationalOrderCode };

            }else {
              this.$message.error('请求错误，检查参数');
              return false;
            }

            if(this.isOdd && !this.isEnd){
              params = {
                ...params,
                personnelRosterNumber,personnelOddNumber,personnelEstimateNumber, personnelEstimatePercentage,
                personnelExcessPercentage,personnelOverridePercentage,
              }

            }else if(this.isEnd){
              params = {
                ...params,
                attendanceWorkerNumber,attendanceOddNumber,actualFinalNumber,actualWorkerNumber,
              }

            }else{
              //处理附件
              const urls = [];
              this.fileList.forEach(item=>{
                if(item.status ==="success"){
                  // urls.push(item.response.fileName);
                  const res = item.response;
                  if(res && res.code && res.code === 200){
                    urls.push(res.fileName);
                  }else if(item.fileName){
                    urls.push(item.fileName);
                  }
                }
              })

              //获取班组名称
              let groupName = null;
              this.groupList.forEach(item=>{
                if(item.workGroupId === groupId){
                  groupName = item.workGroupName;
                }
              });
              //获取方案名称
              let schemeConfigurationName = null;
              this.schemeList.forEach(item=>{
                if(item.id === schemeConfigurationId){
                  schemeConfigurationName = item.programmeName;
                }
              });
              if(groupEstimateNumber*1===0){
                this.msgError('请添加当班预测量');
                return false
              }else if(estimateWorkerNumber === 0){
                this.msgError('请填写预估人数');
                return false
              }
              //获取预估业务量
              params = {
                ...params,
                groupId , groupName, groupEstimateNumber,
                schemeConfigurationId,schemeConfigurationName, standardNumber, recommendedNumber, estimateWorkerNumber,
                estimateEffect,oddJobMale,oddJobFemale,remark,
                urls,deps:this.staffData
              };
            }

            console.log(params);
            // console.log(JSON.stringify(params.deps));
            this.operationalUpdate(params)

          }
        })
      },
      //文件上传长度限制
      handleUploadExceed(file,fileList){
        this.msgError(`最多上传 ${fileList.length} 个附件`)
      },
      //文件删除
      handleUploadRemove(file,fileList){
        this.fileList = fileList;
        // console.log(file,fileList)
      },
      handleUploadPreview(file){
        console.log(file)
        if(file.status === 'success'){
          const res = file.response;
          if(res && res.code && res.code === 200){
            window.location.href = process.env.VUE_APP_BASE_API + "/common/download/resource?resource=" + encodeURI(res.fileName) + "&delete=" + false;
          }else if(file.fileName){
            window.location.href = process.env.VUE_APP_BASE_API + "/common/download/resource?resource=" + encodeURI(file.fileName) + "&delete=" + false;
          }
        }
      },
      //文件状态改变时
      handleUploadChange(file, fileList){
        // console.log(file,fileList);
        if(file.status === 'success'){
          const res = file.response;
          if(res.code && res.code === 200){
            this.fileList = fileList;
          }else {
            this.fileList = fileList.filter(item => item.uid !== file.uid);
            this.msgError(res.msg || '文件上传失败')
          }
        }

        // if(file.status === 'fail'){
        //   this.msgError('文件上传失败')
        // }
        // this.fileList = fileList;
        // console.log(file, fileList)
      },
      // 差额
      getDiffer(a,b){
        const aa = a ? a : 0;
        const bb = b ? b : 0;
        const cc = aa - bb;
        if(cc > 0){
          return "减少 "+ Math.ceil(cc).toFixed(0)
        }else {
          return "增加 "+ Math.abs(cc).toFixed(0)
        }
      },
      //预估定额合计
      getQuotaSum(){
        let number = 0;
        this.staffData.forEach(item => {
          if(item.estimateQuota){
            number += item.estimateQuota;
          }
        });
        return number
      },
      handleChange(data){
        // 预估人数变动
        console.log(data)
        //获取组别数量 定额
        let estimateQuota = 0;
        const tmp = this.staffData.filter(o => o.regionName == data.regionName);
        tmp.forEach(item=>{
          if(!item.postDisable && item.estimatePostNumber){
            estimateQuota += item.estimatePostNumber
          }

        })
        // console.log(tmp,quota)
        const len = this.classAreaLen(data.regionName);
        this.staffData[len].estimateQuota = estimateQuota;

        //预估定额合计
        const number = this.getQuotaSum();
        //预估用工
        this.orderForm.estimateWorkerNumber = number;

        //计算 预估人效=当班预测量/预估用工量的比值
        const { groupEstimateNumber } = this.orderForm;
        if(number && groupEstimateNumber){
          const estimateEffect = groupEstimateNumber * 10000 / number;
          this.orderForm = {
            ...this.orderForm,
            estimateEffect: estimateEffect.toFixed(2)
          }
        }
      },
      computeEstimate(){
        //预估定额合计
        const number = this.getQuotaSum();
        //预估用工
        this.orderForm.estimateWorkerNumber = number;

        //计算 预估人效=当班预测量/预估用工量的比值
        const { groupEstimateNumber } = this.orderForm;
        if(number && groupEstimateNumber){
          const estimateEffect = groupEstimateNumber * 10000 / number;
          this.orderForm = {
            ...this.orderForm,
            estimateEffect: estimateEffect.toFixed(2)
          }
        }
      },

      classGroup(name){  //根据组别名称获取组别数量
        return this.staffData.filter(o => o.groupName == name).length;
      },
      classArea(name){  //根据区域名称获取区域数量
        return this.staffData.filter(o => o.regionName == name).length;
      },
      classGroupLen(name){  //根据组别名称获取该区域第一个岗位的偏移位置
        const tmp = Array.from(this.groupNum);
        const index = tmp.indexOf(name);  //某岗位在全区域中的偏移位置
        let len = 0;
        for (let i = 0;i < index;i++){
          len += this.classGroup(tmp[i]);
        }
        return len;
      },
      classAreaLen(name){  //根据组别名称获取该区域第一个岗位的偏移位置
        const tmp = Array.from(this.areaNum);
        const index = tmp.indexOf(name);  //某岗位在全区域中的偏移位置
        let len = 0;
        for (let i = 0;i < index;i++){
          len += this.classArea(tmp[i]);
        }
        return len;
      },
      objectSpanMethod({ row, column, rowIndex, columnIndex }) {
        // console.log(row,column,rowIndex,columnIndex)
        if (columnIndex === 0 || columnIndex === 5 ) {
          //判断区域rowspan数量
          const len = this.classArea(row.regionName);
          const lenName = this.classAreaLen(row.regionName);
          if (rowIndex === lenName) {   //某区域首位岗位
            return {
              rowspan:len,
              colspan:1
            }
          } else return {   //某区域非首位岗位
            rowspan: 0,
            colspan: 0
          };
        }else if(columnIndex === 1 ){
          //判断区域rowspan数量
          const len = this.classGroup(row.groupName);
          const lenName = this.classGroupLen(row.groupName);
          if (rowIndex === lenName) {   //某班级首位学生行
            return {
              rowspan:len,
              colspan:1
            }
          } else return {   //某班级非首位学生行
            rowspan: 0,
            colspan: 0
          };
        }
      },

      //格式化设备数据
      convertDeviceData(data){
        const deviceData = []
        const deviceTime = [];
        const beginTime = data[0].beginTime;
        const endTime = data[0].endTime;
        data.forEach((item,index) => {
          if(beginTime>endTime){
            //晚班
            for(let i = beginTime,j=0; i< 24; i++,j++){
              item[i] = item.tableData[j];
              //获取设备时间
              if(index === 0){
                deviceTime.push(i)
              }
            }
            for(let i = 0,j=0; i< endTime; i++,j++){
              item[i] = item.tableData[j];
              //获取设备时间
              if(index === 0){
                deviceTime.push(i)
              }
            }
          }else {
            for(let i = beginTime,j=0; i<= endTime; i++,j++){
              item[i] = item.tableData[j];
              //获取设备时间
              if(index === 0){
                deviceTime.push(i)
              }
            }
          }
          deviceData.push(item)
        });
        this.deviceTime = deviceTime;
        return deviceData;
      },
      //获取考勤人数
      getAttendanceInformation(){
        const { timeShiftId,workTime,groupId } = this.orderForm;
        const params = { workTime,groupId, timeShiftId };
        getAttendanceInformation(params).then(res=>{
          console.log(res);
          if(res && res.code === 200){
            const data = res.data || {};
            this.orderForm = {
              ...this.orderForm,
              attendanceWorkerNumber: data.attendanceInformationOfCq, //出勤长期工
              attendanceOddNumber: data.attendanceInformationOfTerm, //出勤临时工
            }
          }
        })
      },
      //获取排班人数
      getWorkerNumber(){
        const { timeShiftId,workTime,groupId, estimateWorkerNumber } = this.orderForm;

        const params = { workTime,groupId, shiftId:timeShiftId };
        // console.log(params);
        getWorkerNumber(params).then(res=>{
          console.log(res);
          if(res && res.code ===200){
            const data = res.data || {};
            const number = data.workNumber ? data.workNumber : 0;
            const strategyCx = data.strategyCx ? data.strategyCx : 0;

            // 预测零工数：- 系统自动填写默认值，可手动修改（增减均可）。- 临时工人数=总用工需求人数-有效在职人数。
            const personnelOddNumber = ( estimateWorkerNumber -number ).toFixed(0)

            this.orderForm = {
              ...this.orderForm,
              personnelRosterNumber: number,
              personnelOddNumber: personnelOddNumber,
              personnelOverridePercentage: strategyCx,    // 用工超控比：用工超额控制比例，从策略配置中取值。
            };

          }
        })

      },
      //订单详情
      getOperationalDetail(id){
        getOperationalDetail(id).then(res=>{
          console.log(res);
          if(res && res.code === 200){
            const data = res.data || {};
            this.order = data;
            //编辑和详情 回写数据
            this.orderForm = {
              ...this.orderForm,
              operationalOrderCode: data.operationalOrderCode,
              workTime: data.workTime,
              timeShiftId: data.timeShiftId,
              forecast24: data.forecast24,
              forecast12: data.forecast12,
              notSentNumber: data.notSentNumber,
              bequeathNumber: data.bequeathNumber,
              quantityToUnloaded: data.quantityToUnloaded,
              carNumber: data.carNumber,
              estimateBusinessNumber: data.estimateBusinessNumber,

              groupId: data.groupId,
              groupEstimateNumber: data.groupEstimateNumber,

              remark: data.remark,

              schemeConfigurationId: data.schemeConfigurationId,
              schemeConfigurationName: data.schemeConfigurationName,
              standardNumber: data.standardNumber,
              recommendedNumber: data.recommendedNumber,
              estimateEffect: data.estimateEffect,
              estimateWorkerNumber: data.estimateWorkerNumber,
              oddJobFemale: data.oddJobFemale,
              oddJobMale: data.oddJobMale,

              personnelRosterNumber: data.personnelRosterNumber, //排班人数
              personnelOddNumber: data.personnelOddNumber, //预测零工数
              personnelEstimateNumber: data.personnelEstimateNumber, //预估用工
              personnelEstimatePercentage: data.personnelEstimatePercentage, //预估人效比(人事)
              personnelExcessPercentage: data.personnelExcessPercentage, //用工超额比
              personnelOverridePercentage: data.personnelOverridePercentage, //用工超控比

              attendanceWorkerNumber: data.attendanceWorkerNumber, //出勤长期工
              attendanceOddNumber: data.attendanceOddNumber, //出勤临时工
              actualFinalNumber: data.actualFinalNumber, //实际完成
              actualWorkerNumber: data.actualWorkerNumber, //实际人效
            }

            if(this.strategyFa){  //自动方案策略
              this.schemeList = [{id:data.schemeConfigurationId,programmeName:data.schemeConfigurationName}];
            }

            if(data.deps){
              //排序
              const staffData  = data.deps;
              staffData.sort((a,b)=>{
                return a.groupId - b.groupId
              })
              this.staffData = staffData
            }
            if(data.equipments){
              //设备配置
              const deviceData = this.convertDeviceData(data.equipments)
              this.deviceData = deviceData;
            }
            if(data.urls){
              const fileList = [];
              const urls = data.urls || [];
              urls.forEach((item,index)=>{
                const num = index+1;
                // const name = item.substring(item.lastIndexOf("/")+1);
                const obj = {
                  name: "附件"+num,
                  fileName: item,
                  url: item
                };
                fileList.push(obj)
              })
              this.fileList = fileList;
            }

            //设置男女比例默认值  用工评估待处理
            if(data.status === 3){
              this.orderForm = {
                ...this.orderForm,
                oddJobMale:80,
                oddJobFemale:20,
              }
            }

            //获取排班人数  并且是 待处理状态
            if(this.isOdd && data.status === 6){
              this.getWorkerNumber();
            }

            //获取 出勤数据  并且是 待处理状态
            if(this.isEnd && this.handleType !=='view'){
              this.getAttendanceInformation()
            }

            if(data.auditLogs){
              this.auditLogs = data.auditLogs;
            }



          }
        })
      },
      //重置 方案数据
      resetScheme(){
        this.staffData = null;
        this.deviceData = null;
        this.deviceTime = null;
        this.orderForm = {
          ...this.orderForm,
          standardNumber: null,
          recommendedNumber: null,
          estimateEffect: null,
          estimateWorkerNumber: null,
        }
      },
      //重置 方案数据
      resetScheme0(){
        this.staffData = null;
        this.deviceData = null;
        this.deviceTime = null;
        this.orderForm = {
          ...this.orderForm,
          schemeConfigurationId: null,
          standardNumber: null,
          recommendedNumber: null,
          estimateEffect: null,
          estimateWorkerNumber: null,
        }
      },
      //获取 自动方案
      getFaResult(){
        const { timeShiftId,groupEstimateNumber } = this.orderForm;
        if(timeShiftId && groupEstimateNumber){
          const params = { timeShiftId, groupEstimateNumber};
          getFaResult(params).then(res=>{
            console.log(res);
            if(res && res.code === 200){
              const data = res.data || {};
              const scheme = data.faResult;
              this.currScheme = scheme;

              this.schemeList = [scheme];

              this.getSchemeDetail(scheme.id)
            }else {
              this.resetScheme0()
            }
          }).catch(err=>{
            console.log(err)
            this.resetScheme0()
          })
        }else {
          this.resetScheme0()
        }
      },
      //修改 当班预测量 获取数据
      changeGroupEstimate(){
        if(this.strategyFa){ //自动方案
          this.getFaResult()
        }else {
          //手动方式获取计算数据
          this.getComputedResult()
        }
      },
      //获取 实际完成 数据
      getComputedEnd(){
        const { attendanceWorkerNumber, attendanceOddNumber, actualFinalNumber } = this.orderForm;
        const number = attendanceWorkerNumber*1 + attendanceOddNumber*1
        const actualWorkerNumber = number ? actualFinalNumber * 10000 / number : 0;
        this.orderForm = {
          ...this.orderForm,
          actualWorkerNumber:actualWorkerNumber.toFixed(2)
        }
      },
      //获取 零工计算 数据
      getComputedOdd(){
        const { personnelRosterNumber, personnelOddNumber, groupEstimateNumber,recommendedNumber } = this.orderForm;
        if(!isNaN(personnelRosterNumber) && !isNaN(personnelOddNumber)){
          //预估用工：排班人数+零工人数
          const personnelEstimateNumber = (personnelRosterNumber*1 + personnelOddNumber*1).toFixed(0);
          this.orderForm = {
            ...this.orderForm,
            personnelEstimateNumber:personnelEstimateNumber,
          }

          //预估人效比：预估业务总量 / 人事预估用工数
          //预估人效比：当班预测量 / 人事预估用工数  需求修改2022/2/17
          if(personnelEstimateNumber){
            // const personnelEstimatePercentage = (estimateBusinessNumber*10000 / personnelEstimateNumber).toFixed(2);
            const personnelEstimatePercentage = (groupEstimateNumber*10000 / personnelEstimateNumber).toFixed(2);
            this.orderForm = {
              ...this.orderForm,
              personnelEstimatePercentage
            }

            // 用工超额比：预估用工超额比例=（人事预估用工量 - 建议人数）/建议人数*100%
            if(recommendedNumber){
              const personnelExcessPercentage = (personnelEstimateNumber - recommendedNumber ) / recommendedNumber *100;
              this.orderForm = {
                ...this.orderForm,
                personnelExcessPercentage: personnelExcessPercentage.toFixed(2)
              }
            }
          }

        }
      },
      //获取计算数据
      getComputedResult(){
        const scheme = this.currScheme;
        console.log(scheme)
        const { groupEstimateNumber,estimateWorkerNumber } = this.orderForm;
        if(scheme && scheme.id){
          this.orderForm = {
            ...this.orderForm,
            standardNumber:scheme.standardNumber,
            schemeConfigurationId:scheme.id,
          }
          if(groupEstimateNumber && !isNaN(groupEstimateNumber)){
            //计算建议人数 当班预测量 / 对应运营方案设置的人效
            const recommendedNumber = groupEstimateNumber*10000 / scheme.standardEffect;
            this.orderForm = {
              ...this.orderForm,
              recommendedNumber: Math.ceil(recommendedNumber)
            }
            //计算 预估人效=当班预测量/预估用工量的比值
            if(estimateWorkerNumber){
              const estimateEffect = groupEstimateNumber * 10000 / estimateWorkerNumber;
              this.orderForm = {
                ...this.orderForm,
                estimateEffect: estimateEffect.toFixed(2)
              }
            }
          }else {
            this.orderForm = {
              ...this.orderForm,
              // standardNumber: null,
              recommendedNumber: null,
              estimateEffect: null,
            }
          }
        }

      },
      //获取方案详情
      getSchemeDetail(id){
        this.resetScheme();
        getSchemeDetail(id).then(res=>{
          console.log(res);
          if(res && res.code ===200){
            const data = res.data;
            if(data){
              const scheme = data.schemeConfiguration
              //当前选择的方案
              console.log(scheme)
              this.currScheme = scheme;
              const staffData = data.deps;
              const enableStaff = [];
              staffData.forEach(item=>{
                if(!item.postDisable){
                  item.estimatePostNumber = item.postNumber;
                  item.estimateQuota = item.quota;
                  enableStaff.push(item)
                }
              })
              //人员配置
              this.staffData = enableStaff;
              //计算预估用工 人效
              this.computeEstimate()
              //设备配置
              const deviceData = this.convertDeviceData(data.equipments)
              this.deviceData = deviceData;

              this.$nextTick(() => {
                //计算 建议人数 预估人效 计算数据
                this.getComputedResult()
              })
            }



          }
        }).catch(err=>{
          console.log(err);
          this.resetScheme()
        })
      },
      //切换方案
      handleChangeScheme(id){
        console.log(id);

        this.schemeList.forEach(item=>{
          if(item.id === id){
            console.log(item);
            //当前选择的方案
            this.currScheme = item;
            this.orderForm = {
              ...this.orderForm,
              standardNumber:item.standardNumber,
              recommendedNumber:null,
              estimateEffect:null,
              estimateWorkerNumber:null,
            }
          }
        });

        //获取方案详情
        this.getSchemeDetail(id);
      },
      //班次获取
      getTimShiftInfo(){
        getTimShiftInfo().then(res=>{
          if(res && res.code === 200){
            this.timeShiftList= res.rows;
          }
        });
      },
      //班次获取 班组 方案 策略
      getTimeShiftAndDep(){
        getTimeShiftAndDep().then(res=>{
          console.log(res)
          if(res && res.code === 200){
            const data = res.data || {};

            this.groupList= data.deps;
            this.timeShiftList= data.timeShift;
            this.strategyFa= !!data.strategyFa;

            if(!data.strategyFa){  //手动方案策略
              this.schemeList = data.faResult;
            }
            // this.schemeList = data.faResult;

            if(this.id){
              //获取订单详情
              this.getOperationalDetail(this.id)
            }

          }
        });
      },
    },


  };
</script>

<style>
  .employeeWorker .el-divider{
    margin: 1px 0 18px;
  }
</style>
